import {
  SaaSRolePageParams,
  SaaSRoleListItem,
  SaaSRoleListGetResultModel,
  SaaSRoleDetailParams,
  SaaSMenuListItem,
  SaaSUserRoleItem,
} from './model/roleModel';

import { authorityHttp } from '/@/utils/http/axios';

enum Api {
  SaaSRolePageList = '/v1/role/getList',
  SaaSRoleDetail = '/v1/role/detail',
  SaaSRoleEdit = '/v1/role/update',
  SaaSRoleCreate = '/v1/role/create',
  SaaSRoleDelete = '/v1/role/delete/',
  SaaSRoleAllList = '/v1/user/role/getAllList',
  SaaSRoleList = '/v1/role/getRoleListByApp',
  SaaSResourceTree = '/resource/getMenuElementResource',
}

export const getSaaSRoleListAll = () => {
  return authorityHttp.get<SaaSUserRoleItem[]>({ url: Api.SaaSRoleAllList });
};

export const getSaaSRoleListByPage = (params?: SaaSRolePageParams) =>
  authorityHttp.get<SaaSRoleListGetResultModel>({ url: Api.SaaSRolePageList, params });

export const getSaaSRoleDetail = (params: SaaSRoleDetailParams) =>
  authorityHttp.get<SaaSRoleListItem>({ url: Api.SaaSRoleDetail, params });

export const editSaaSRole = (params: SaaSRoleListItem) => authorityHttp.post<string>({ url: Api.SaaSRoleEdit, params });

export const createSaaSRole = (params: SaaSRoleListItem) =>
  authorityHttp.post<string>({ url: Api.SaaSRoleCreate, params });

export const deleteSaaSRole = (params: any) => {
  return authorityHttp.delete<string>({ url: Api.SaaSRoleDelete + params });
};

const changeKey = (tree: any) => {
  tree.key = tree.id;
  tree.title = tree.resourceName;
  if (tree.children !== undefined) {
    tree.children?.forEach((item) => {
      changeKey(item);
    });
  }
};

export const getAppResourceTree = async (params: { appId: string }) => {
  const res = await authorityHttp.get<SaaSMenuListItem[]>({ url: Api.SaaSResourceTree, params });
  res.forEach((item) => {
    changeKey(item);
  });
  return res;
};

export const getRoleList = (params: { subAppId: string }) => {
  return authorityHttp.get({
    url: Api.SaaSRoleList,
    params,
  });
};
